<?php
/**
 *
 *
 */
class Yz_Action_Insert
    extends Yz_Action_Abstract
{

    /**
     *  @var array( fieldName: fieldSelectClause )
     */
    protected $fields = array();

    protected $references = array();

    /**
     *  @var Item
     */
    protected $values;


    /************************************
     *          Public methods          *
     ************************************/

    /**
     *  @return int
     */
    public function getInsertId()
    {
        if (! $this->executed)
            throw new Yz_Action_Exception_NotExecutedYet();
        return $this->statement->getInsertId();
    }


    /************************************
     *        Protected methods         *
     ************************************/



    /**
     *  Common Insert statement creator:
     *      the common part of statement
     *  @return Yz_SQL_Statement_Insert
     */
    protected function buildStatement()
    {
        debug();
        $this->inspectModel();
        return Yz_SQL_Statement_Insert::create()
            ->insert(current($this->tables))
            ->set($this->fields)
        ;
    }



    /**
     *  Inspect model's property and create a field clause or
     *      recursively inspect referenced model
     *  @param Yz_Model_Interface $model
     *  @param string $name
     *  @param Yz_Property_Interface $prop
     *  @return this
     */
    protected function inspectField(Yz_Model_Interface $model, $alias, $propName, Yz_Property_Interface $prop)
    {
        debug();
        if ($prop instanceof Yz_Property_Id) {
            // use a DEFAULT value for primary key
            $clause = "DEFAULT";
        } else if ($prop instanceof Yz_Property_Interface_ReferenceList) {
            // ### skip referenced models
            $clause = false;
        } else if ($prop instanceof Yz_Property_OneToOne) {
            $clause = false;
        } else if ($prop instanceof Yz_Property_Interface_Reference) {
            // ### handle referenced items
            $this->references[] = $propName;
            $clause = ":{$propName}";
            $propName .= 'Id';
        } else {

            // TODO check custom settings for the field
            $clause = ":{$propName}";
        }

        $clause
            and $this->fields[$propName] = $clause;
        return $this;
    }

}
